

function contact_change()
{
   var contactid="";
   var telephone2=""; var fax="";
   
   var lookupItem = new Array(); 
   lookupItem = Xrm.Page.getAttribute("primarycontactid").getValue();
   if (lookupItem!=null) contactid=lookupItem[0].id;

   
   if (contactid!="")
   {
      var obj_contact=RetrieveEntityById("contact",contactid,"mobilephone,emailaddress1");
      telephone2=obj_contact.mobilephone;
      fax=obj_contact.emailaddress1;  

 }
   
   Xrm.Page.getAttribute("telephone2").setValue(telephone2);         
   Xrm.Page.getAttribute("fax").setValue(fax);	


}

function RetrieveEntityById(EntityName, EntityId, EntityColumns) {
    var resultXml, errorCount, msg, xmlHttpRequest;
    var arrayEntityColumns = EntityColumns.split(",");
    var xmlEntityColumns = '';
    for (var i = 0; i < arrayEntityColumns.length; i++) {
        xmlEntityColumns += "<q1:Attribute>" + arrayEntityColumns[i] + "</q1:Attribute>";
    }
    var soap = PopulateSoapObject(); // //Prepare the SOAP message.
    var xml = soap.Header
        + "<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"
        + "<entityName>" + EntityName + "</entityName>"
        + "<id>" + EntityId + "</id>"
        + "<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>"
        + "<q1:Attributes>" + xmlEntityColumns + "</q1:Attributes>"
        + "</columnSet>"
        + "</Retrieve>"
        + soap.Footer;
    //call function to create Soap Request to ms crm webservice 
    xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false); // false = don't make async call 
    xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);
    // debugger;
    resultXml = xmlHttpRequest.responseXML;
    return ObjectFromXML(resultXml, arrayEntityColumns, "//RetrieveResult");
}

function PopulateSoapObject() {
    var soap = new Object();
    soap.Header = "<?xml version='1.0' encoding='utf-8'?>"
        + "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'"
        + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"
        + " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"
        + Xrm.Page.context.getAuthenticationHeader() + "<soap:Body>";
    soap.Footer = "</soap:Body></soap:Envelope>";
    return soap;
}

ObjectFromXML = function (xml, arrFields, prefix, ignoreNulls) {
    var r = {}; // Return object
    r.ok = false;
    if (xml == null) { r.errorMsg = "No XML Returned by platform!"; return r };
    var errorCount = xml.selectNodes('//error').length;
    if (errorCount != 0) {
        r.errorMsg = xml.selectSingleNode('//description').nodeTypedValue;
        return r;
    }
    if (xml == null) {
        r.errorMsg = "Null XML returned.";
        return r;
    }
    /* var recordCount = 0;
    $(xml).find(prefix.substr(2)).each(function () {
    recordCount++;
    });
    if (recordCount == 0) {
    r.errorMsg = "No Records returned.";
    return r;
    } */
    if (prefix != "") { xml = xml.selectSingleNode(prefix) }; // Grab just the first node with the prefix
    // Everything ok, now format as an object
    r.ok = true;
    for (var i = 0; i < arrFields.length; i++) {
        if (!ignoreNulls) { r[arrFields[i]] = "" }
        var node = xml.selectSingleNode("q1:" + arrFields[i]);
        if (node != null) {
            var lookup = false;
            if (arrFields[i].indexOf("id") >= 0) {
                try { // Add try loop as .text fails when atribute not present
                    var name = node.getAttributeNode("name").text;
                    var type = node.getAttributeNode("type").text;
                    if (name != null && type != null) { lookup = true }
                } catch (err) { };
            }
            if (lookup) {
                r[arrFields[i]] = { name: name, id: node.text, entityType: type} // return lookup object 
            } else {
                r[arrFields[i]] = node.text;
            }
        }
    } // for
    return r;
}             // ObjectFromXML


